/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("pagination");
    var util = require("util");
    require("./common");
    var Template = require("/public/js/lib/template");
    var Highcharts = require("/public/js/lib/highcharts/js/highcharts");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'commonModule']);

    // 查询服务
    function queryService($http, $q, baseData) {
        var service = {
            // 是否有数据
            hasData: true,
            // 图表周期
            chartCycle: '1',
            // 明细周期
            detailCycle: '1',
            // 汇总数据
            chartData: undefined,
            // 明细数据
            detailData: undefined,

            // =======================数据转化 start====================================
            convertData: function (data) {
                var i, length = 0, custData = {}, categories = [], temp, j,
                    series = [
                        { name: '推荐转到访', color: baseData.colorArray[0], data: [] },
                        { name: '到访转认购（含直签）', color: baseData.colorArray[1], data: [] },
                        { name: '推荐转签约', color: baseData.colorArray[2], data: [] }
                    ];

                for (i in data) {
                    if (data.hasOwnProperty(i)) {
                        switch (i) {
                        case 'cj2dkRate':
                            //带看转成交转化率
                            temp = series[1].data;
                            break;
                        case 'qy2tjRate':
                            //推荐转成交转化率
                            temp = series[2].data;
                            break;
                        case 'dk2tjRate':
                            //推荐转带看转化率
                            temp = series[0].data;
                            break;
                        }

                        length = data[i].length;

                        for (j = 0; j < length; j++) {
                            i == 'cj2dkRate' && categories.unshift(data[i][j].xdate);
                            temp.unshift(parseFloat(data[i][j][i]) || 0); //ps: 名称一致
                        }
                    }
                }

                custData.step = length > 0 ? Math.ceil(length / 4) : 1;
                custData.maxStaggerLines = 1;
                custData.categories = categories;
                custData.series = series;

                return custData;
            },

            convertData2: function (data) {
                var i, temp, j,
                    custData = {
                        rowCount: data.rowCount,
                        data: []
                    };

                for (i in data.detail) {
                    if (data.detail.hasOwnProperty(i)) {
                        if (i !== 'data') {
                            custData[i] = data.detail[i];
                        } else {
                            custData.data = [];
                            for (j in data.detail.data) {
                                if (data.detail.data.hasOwnProperty(j)) {
                                    custData.data.push(data.detail.data[j]);
                                }
                            }
                        }
                    }
                }

                return custData;
            },

            
            // =======================图表数据结构 start======================================
            dataDefault: {
                chart: {
                    marginTop: 50
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '转化率(%)',
                    align: 'left'
                },
                xAxis: {
                    tickWidth: 0,
                    labels: {
                        step: 1
                    },
                    categories: []//['01-01', '01-02', '01-03', '01-04', '01-05', '01-06','01-07', '01-08', '01-10', '01-11', '01-12', '01-13']
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    min: 0,
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }],
                    gridLineColor: '#EBEBEB',
                    labels: {
                        formatter: function () {
                            return this.value + '%';
                        }
                    }
                },
                tooltip: {
                    shared: true,
                    valueSuffix: ' %'
                    /*formatter: function() {
                        return this.y * 100;
                    }*/
                },
                legend: {
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true
                },
                credits: { // 版权
                    enabled: false
                },
                series: []/*[{
            name: '项目1',
            color: 'red',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        }, {
            name: '项目2',
            data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
        }, {
            name: '项目3',
            data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
        }, {
            name: '项目4',
            data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
        }]*/
            },
        // =======================图表数据结构 end==================================

            query: function() {
                service.queryChart();
                service.queryDetail();
            },

            // 获取图表数据
            queryChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.chartCycle = baseData.getValidCycle(service.chartCycle);
                var url = '/api/index.php?r=olap/cst-transform/get-kh-change-rate-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.chartData = data.data;
                    });
            },

            // 获取明细数据
            queryDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.pageSize;
                var url = '/api/index.php?r=olap/cst-transform/get-kh-change-rate-detail-info';

                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.pageIndex = filters.pageIndex;
                        service.total = data.data.rowCount;
                        service.detailData = data.data;
                    });
            },

            // 导出数据
            exportData: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                var url = '/api/index.php?r=olap/cst-transform/export';
                util.download(url, filters);
            }
        };

        return service;
    }
    app.factory('query', ['$http', '$q', 'baseData', queryService]);

    var route = function($routeProvider) {
        $routeProvider
            .when('/1', {
                templateUrl: 'views/client-increase/tj.html',
                controller: 'ViewController',
                resolve: {
                    routeData: function() {
                        return {
                        };
                    }
                }
            })
            .when('/2', {
                templateUrl: 'views/client-increase/dk.html',
                controller: 'ViewController',
                resolve: {
                    routeData: function() {
                        return {
                        };
                    }
                }
            })
            .otherwise({ redirectTo: '/1' });
    };
    app.config(['$routeProvider', route]);

    function StatisticsController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;
    }
    app.controller('StatisticsController', ['$scope', '$location', 'baseData', 'query', StatisticsController]);

    function SearchController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        $scope.$watch('baseData.projectIds', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.query();
            }
        });

        $scope.$watch('query.chartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryChart();
            }
        });

        $scope.$watch('query.detailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryDetail();
            }
        });

        $scope.$watch('query.chartData', function (newValue) {
            if (newValue !== undefined) {
                var chartData = query.convertData(newValue);
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault, {
                    chart: {
                        renderTo: 'graphic_01'
                    },
                    xAxis: {
                        categories: chartData.categories,
                        labels: {
                            step: chartData.step
                        }
                    },
                    series: chartData.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.detailData', function (newValue) {
            if (newValue !== undefined) {
                var detailData = query.convertData2(newValue);
                var html = Template($('#templ_table').html(), detailData, baseData.formatData);
                $('#table_content').html(html);
            }
        });
    }
    app.controller('SearchController', ['$scope', '$location', 'baseData', 'query', SearchController]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});